<template>
  <view class="coupon-page">
    <!-- 顶部导航标签 -->
    <view class="main-tabs">
      <view 
        class="main-tab" 
        :class="{ active: activeMainTab === 'charging' }"
        @click="switchMainTab('charging')"
      >
        <text class="tab-text">充电券({{ mainCounts.charging }})</text>
        <text class="tab-count" :class="{ active: activeMainTab === 'charging' }"></text>
      </view>
      <!--
      <view class="tab-divider"></view>
      -->
      <view 
        class="main-tab" 
        :class="{ active: activeMainTab === 'dining' }"
        @click="switchMainTab('dining')"
      >
        <text class="tab-text">餐饮券({{ mainCounts.dining }})</text>
        <text class="tab-count" :class="{ active: activeMainTab === 'dining' }"></text>
      </view>
      <!--
      <view class="tab-divider"></view>
      -->
      <view 
        class="main-tab" 
        :class="{ active: activeMainTab === 'peripheral' }"
        @click="switchMainTab('peripheral')"
      >
        <text class="tab-text">周边({{ mainCounts.peripheral }})</text>
        <text class="tab-count" :class="{ active: activeMainTab === 'peripheral' }"></text>
      </view>
    </view>
    <view class="sub-tabs-container">
      <!-- 子标签 -->
      <view class="sub-tabs">
        <view 
          class="sub-tab" 
          :class="{ active: activeSubTab === 'unused' }"
          @click="switchSubTab('unused')"
        >
          未使用({{ counts.unused }})
        </view>
        <view 
          class="sub-tab" 
          :class="{ active: activeSubTab === 'used' }"
          @click="switchSubTab('used')"
        >
          已使用({{ counts.used }})
        </view>
        <view 
          class="sub-tab" 
          :class="{ active: activeSubTab === 'expired' }"
          @click="switchSubTab('expired')"
        >
          已失效({{ counts.expired }})
        </view>
      </view>

      <!-- 卡券列表 -->
      <scroll-view scroll-y="true" class="coupon-list">
        <!-- 动态生成卡券卡片 -->
        <view 
          class="coupon-card" 
          :class="{ 'coupon-card-used': coupon.status === 'used', 'coupon-card-expired': coupon.status === 'expired' }"
          v-for="(coupon, index) in filteredCouponList" 
          :key="coupon.id"
        >
          <view class="coupon-status" v-if="coupon.statusTag && coupon.statusTag.text">
            <text class="status-tag">{{ coupon.statusTag.text }}</text>
          </view>
          <view class="coupon-header">
            <view class="coupon-info">
              <text class="coupon-title">{{ coupon.title }}</text>
              <text class="coupon-expire">{{ coupon.expireTime }} 到期</text>
              <text class="coupon-restriction">{{ coupon.restriction }}</text>
            </view>
            <view class="coupon-value">
              <text class="value-amount">¥{{ coupon.amount }}</text>
              <text class="value-condition">{{ coupon.condition }}</text>
            </view>
          </view>
          <view class="coupon-details">
            <view class="detail-divider"></view>
            <view class="detail-row">
              <view class="detail-content" @click="toggleDetail(index)">
                <text class="detail-text">{{ expandedDetails[index] ? coupon.fullDetailText : coupon.detailText }}</text>
                <uni-icons class="detail-arrow" color="#999" :type="expandedDetails[index] ? 'up' : 'down'" size="15"></uni-icons>
              </view>
              <view class="coupon-action" v-if="coupon.actionText">
                <view class="use-btn" @click="goToNearbyStations(coupon)">{{ coupon.actionText }}</view>
              </view>
            </view>
          </view>
        </view>

        <!-- 底部提示 -->
        <!--
        <view class="list-end">
          <view class="end-line"></view>
          <text class="end-text">- 已经到底了 -</text>
          <view class="end-line"></view>
        </view>
        -->
      </scroll-view>
    </view>

  </view>
</template>

<script>
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { page as fetchMealTickets } from '@/api/tmealticket/index.js'

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      activeMainTab: 'charging',
      activeSubTab: 'unused',
      expandedDetails: [],
      couponList: [],
      mainCounts: { // 新增主标签数量
        charging: 0,
        dining: 0,
        peripheral: 0
      }
    }
  },
  computed: {
    // 当前主类别下的券集合（目前仅餐饮券有数据，其他类别为空）
    currentCategoryCoupons() {
      if (this.activeMainTab === 'dining') {
        return this.couponList;
      }
      return [];
    },
    filteredCouponList() {
      // 二级筛选：在当前主类别集合下按状态过滤
      return this.currentCategoryCoupons.filter(coupon => {
        if (this.activeSubTab === 'unused') return coupon.status === 'unused';
        if (this.activeSubTab === 'used') return coupon.status === 'used';
        if (this.activeSubTab === 'expired') return coupon.status === 'expired';
        return true;
      });
    },
    counts() {
      const counts = { unused: 0, used: 0, expired: 0 };
      // 仅统计当前主类别下的数量
      this.currentCategoryCoupons.forEach(coupon => {
        if (coupon.status === 'unused') {
          counts.unused++;
        } else if (coupon.status === 'used') {
          counts.used++;
        } else if (coupon.status === 'expired') {
          counts.expired++;
        }
      });
      return counts;
    }
  },
  methods: {
    switchMainTab(tab) {
      this.activeMainTab = tab;
      this.loadCoupons(); // 切换主标签时重新加载数据
    },
    switchSubTab(tab) {
      this.activeSubTab = tab;
      this.loadCoupons(); // 切换子标签时重新加载数据
    },
    toggleDetail(index) {
      // 直接使用传入的索引，因为expandedDetails应该与filteredCouponList对应
      this.$set(this.expandedDetails, index, !this.expandedDetails[index]);
    },
    async loadCoupons() {
      try {
        // 旧页默认 rows=100000, state:''
        const res = await fetchMealTickets({ rows: 100000, state: '' });
        if (res && res.code === 0 && res.success && res.data && Array.isArray(res.data.records)) {
          const nowTs = Date.now();
          const THREE_DAYS = 3 * 24 * 60 * 60 * 1000;
          const records = res.data.records;
          this.couponList = records.map(r => {
            const id = r.id || r.ticketNo;
            const title = r.productName || '优惠券';
            const expireTime = (r.expiryDate || '').replace('T', ' ');
            const amount = String(r.faceValue ?? '');
            const condition = r.scope || '无门槛';
            const restriction = r.ruleTag || r.serviceTag || '';
            const expTs = expireTime ? new Date(expireTime.replace(/-/g, '/')).getTime() : 0;
            const isExpired = expTs && expTs < nowTs;
            const used = Number(r.writeOff) === 1;
            const status = used ? 'used' : (isExpired ? 'expired' : 'unused');
            const nearExpire = !used && !isExpired && expTs && (expTs - nowTs) <= THREE_DAYS;
            const statusTag = { text: nearExpire ? '快到期' : '' };
            const actionText = status === 'unused' ? '去使用' : '';
            const detailText = `使用范围：${r.scope || '门店可用'}；规则：${restriction || '按券面规则使用'}`;
            const fullDetailText = `使用范围：${r.scope || '门店可用'}\n规则：${restriction || '按券面规则使用'}\n来源：${r.source || ''}`;
            return {
              id,
              title,
              expireTime,
              restriction,
              amount,
              condition,
              statusTag,
              actionText,
              detailText,
              fullDetailText,
              status
            };
          });
          // 重置展开状态 - 使用最大可能长度来避免索引越界
          this.expandedDetails = new Array(Math.max(this.couponList.length, 100)).fill(false);
          // 主标签统计：当前接口仅餐饮券
          this.mainCounts = {
            charging: 0,
            dining: records.length,
            peripheral: 0
          };
        } else {
          uni.showToast({ title: (res && res.msg) || '加载卡券失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '网络异常，加载卡券失败', icon: 'none' });
        console.error('loadCoupons error', e);
      }
    },
    goToNearbyStations(coupon) {
      // 跳转到券详情页面，携带券的id
      uni.navigateTo({
        url: `/packages/oldpages/pages/certificate2/index?id=${coupon.id}`
      });
    }
  },
  onLoad() {
    this.loadCoupons();
  }
}
</script>

<style scoped>
.sub-tabs-container {
  background: #fafaf8;
}

.coupon-page {
  min-height: 100vh;
  padding: 0;
}

/* 顶部导航标签 */
.main-tabs {
  background: linear-gradient(to bottom, #fcefe7, #fff);
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
}

.main-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx 0 0 0;
  position: relative;
}

.tab-text {
  font-size: 32rpx;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.main-tab.active .tab-text {
  color: #fd525a;
}

.tab-count {
  font-size: 24rpx;
  color: #999;
  padding: 4rpx 20rpx;
  border-radius: 12rpx;
  display: inline-block;
}

.tab-count.active {
  background: #fd525a;
  color: #fff;
}

.tab-divider {
  width: 1rpx;
  height: 40rpx;
  background: #e0e0e0;
  margin: 0 20rpx;
}

/* 子标签 */
.sub-tabs {
  background: #fff;
  display: flex;
  padding: 20rpx 30rpx;
}

.sub-tab {
  flex: 1;
  text-align: center;
  padding: 8rpx 4rpx;
  font-size: 28rpx;
  color: #666;
  background: #f8f8f8;
  margin: 0 20rpx;
  border-radius: 48rpx;
  border: 2rpx solid transparent;
}

.sub-tab.active {
  background: #fff5f0;
  color: #fd525a;
  border-color: #fd525a;
}

/* 卡券列表 */
.coupon-list {
  height: calc(100vh - 200rpx);
  margin-top: 20rpx;
}

.coupon-card {
  background: #fff;
  border-radius: 16rpx;
  margin: 0 auto 20rpx auto;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  width: 85%;
  position: relative;
}

.coupon-card-used {
  background: #fff; /* 已使用背景色 - 白色 */
}

.coupon-card-used .value-amount,
.coupon-card-used .value-condition {
  color: #999;
}

.coupon-card-used .coupon-status {
  background: #e5e5e5;
}

.coupon-card-used .status-tag {
  color: #999;
}

.coupon-card-expired {
  background: #fff; /* 已失效背景色 - 白色 */
}

.coupon-card-expired .value-amount,
.coupon-card-expired .value-condition {
  color: #999;
}

.coupon-card-expired .coupon-status {
  background: #e5e5e5;
}

.coupon-card-expired .status-tag {
  color: #999;
}

/* 卡券头部 */
.coupon-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
  margin-top: 10rpx;
}

.coupon-info {
  flex: 1;
}

.coupon-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.coupon-expire {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 8rpx;
}

.coupon-restriction {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.coupon-value {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 40%;
}

.value-amount {
  font-size: 48rpx;
  font-weight: bold;
  color: #fd525a;
  display: block;
}

.value-condition {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.coupon-status {
  background: linear-gradient(180deg, #b97a56 0%, #eac9b0 100%);
  border-bottom-right-radius: 16rpx;
  padding: 0 24rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: -5rpx;
  left: -5rpx;
}

.status-tag {
  color: #fff;
  font-size: 22rpx;
  font-weight: bold;
}

/* 卡券操作 */
.coupon-action {
  margin-left: 20rpx;
}

.use-btn {
  background: #fd525a;
  color: #fff;
  font-size: 24rpx;
  padding: 12rpx 32rpx;
  border-radius: 44rpx;
  min-width: 86rpx;
  text-align: center;
}

/* 卡券详情 */
.coupon-details {
  padding-top: 20rpx;
}

.detail-divider {
  height: 1rpx;
  background: transparent;
  margin-bottom: 15rpx;
  position: relative;
  overflow: hidden;
}

.detail-divider::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1rpx;
  background: linear-gradient(to right, #e0e0e0 0, #e0e0e0 4rpx, transparent 4rpx, transparent 8rpx);
  background-size: 8rpx 1rpx;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.detail-text {
  font-size: 24rpx;
  color: #999;
}

.detail-arrow {
  margin-left: 10rpx;
}

/* 立即使用按钮 */
.use-now-section {
  margin-top: 20rpx;
  text-align: center;
  padding: 0 20rpx;
}

.use-now-btn {
  background: linear-gradient(135deg, #fc7700 0%, #ff9500 100%);
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  padding: 16rpx 40rpx;
  border-radius: 44rpx;
  min-width: 200rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(252, 119, 0, 0.3);
  transition: all 0.3s ease;
}

.use-now-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(252, 119, 0, 0.3);
}


/* 底部提示 */
.list-end {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.end-line {
  flex: 1;
  height: 1rpx;
  background: #e0e0e0;
  background-image: linear-gradient(to right, transparent 50%, #e0e0e0 50%);
  background-size: 8rpx 1rpx;
}

.end-text {
  font-size: 24rpx;
  color: #999;
  margin: 0 20rpx;
}
</style> 